package com.ssy.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssy.common.CodeMsg;
import com.ssy.common.Constant;
import com.ssy.common.utils.PageResult;
import com.ssy.common.utils.Result;
import com.ssy.system.mapper.RoleMapper;
import com.ssy.system.pojo.Role;
import com.ssy.system.service.IRoleService;
import com.ssy.system.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ssy
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;


    @SuppressWarnings("unchecked")
    @Override
    public PageResult loadAllRolePage(RoleVo roleVo) {
        Page<Role> page = new Page<>(roleVo.getPage(), roleVo.getLimit());
        IPage<Role> roleIPage = this.roleMapper.selectPage(page, new LambdaQueryWrapper<Role>()
                .like(StringUtils.hasText(roleVo.getName()), Role::getName, roleVo.getName())
                .eq(roleVo.getState() != null, Role::getState, roleVo.getState())
                .ge(roleVo.getBeginTime() != null, Role::getCreateTime, roleVo.getBeginTime())
                .le(roleVo.getEndTime() != null, Role::getCreateTime, roleVo.getEndTime())
                .ne(Role::getId, 1)
                .orderByDesc(Role::getLv));
        return new PageResult(roleIPage.getTotal(), roleIPage.getRecords());
    }

    @Override
    public Result insertRole(Role role) {
        if (role == null) {
            return new Result(CodeMsg.ADD_ERROR);
        }
        int i = this.roleMapper.insert(role);
        return i > 0 ? new Result(CodeMsg.ADD_SUCCESS) : new Result(CodeMsg.ADD_ERROR);
    }

    @Override
    public Result updateRole(Role role) {
        if (role == null) {
            return new Result(CodeMsg.UPDATE_ERROR);
        }
        int i = this.roleMapper.updateById(role);
        return i > 0 ? new Result(CodeMsg.UPDATE_SUCCESS) : new Result(CodeMsg.UPDATE_ERROR);
    }

    @Override
    public Result deleteRoleById(Integer id) {
        if (id == null) {
            return new Result(CodeMsg.DELETE_ERROR);
        }
        int i = this.roleMapper.deleteById(id);
        return i > 0 ? new Result(CodeMsg.DELETE_SUCCESS) : new Result(CodeMsg.DELETE_ERROR);
    }

    @Override
    public Result bathDeleteRole(Integer[] ids) {
        if (ids == null || ids.length == 0) {
            return new Result(CodeMsg.DELETE_ERROR);
        }
        ArrayList<Serializable> idList = new ArrayList<>();
        for (Integer id : ids) {
            idList.add(id);
        }
        this.roleMapper.deleteBatchIds(idList);
        return new Result(CodeMsg.DELETE_SUCCESS);
    }


    @Override
    public Result queryRolesByUserId(Integer userId) {
        List<Role> roles = this.roleMapper.selectList(new LambdaQueryWrapper<Role>()
                .eq(Role::getState, Constant.STATE)
                .notIn(Role::getId, 1));
        List<Integer> roleIds = this.roleMapper.selectRoleIdsByUserId(userId);

        //用于装当前用户的角色
        List<Role> currentUserRoles = new ArrayList<>();
        if (roleIds != null && roleIds.size() > 0) {
            currentUserRoles = this.roleMapper.selectList(new LambdaQueryWrapper<Role>()
                    .eq(Role::getState, Constant.STATE)
                    .in(Role::getId, roleIds));
        }

        //构建复选框的List
        List<Map<String, Object>> res = new ArrayList<>();
        for (Role r1 : roles) {
            boolean LAY_CHECKED = false;
            for (Role r2 : currentUserRoles) {
                if (r1.getId() == r2.getId()) {
                    LAY_CHECKED = true;
                    break;
                }
            }
            Map<String, Object> map = new HashMap<>();
            map.put("id", r1.getId());
            map.put("name", r1.getName());
            map.put("remark", r1.getRemark());
            map.put("LAY_CHECKED", LAY_CHECKED);
            res.add(map);
        }
        return new Result(res);
    }

    @Override
    public List<String> queryRoleNamesByUserId(Integer id) {
        //查询当前用户拥有的角色ID
        List<Integer> roleIds = this.roleMapper.selectRoleIdsByUserId(id);
        List<Role> currentUserRoles = new ArrayList<>();
        if (roleIds != null && roleIds.size() > 0) {
            currentUserRoles = this.roleMapper.selectList(new LambdaQueryWrapper<Role>()
                    .eq(Role::getState, Constant.STATE));
        }
        List<String> roles = new ArrayList<>();
        for (Role role : currentUserRoles) {
            roles.add(role.getName());
        }
        return roles;
    }

    @Override
    public void saveRolePermission(Integer roleId, Integer[] pids) {
        this.roleMapper.deleteRolePermissionByRid(roleId);
        if (pids != null && pids.length > 0) {
            for (Integer pid : pids) {
                this.roleMapper.saveRolePermission(roleId, pid);
            }
        }
    }

}
